<template>
  <div class="mmv-map-page custom_card">
    <div class="mmv-side-bar" v-loading="timerLoading">
      <div class="refreshCountdown-carInfo">
        <i class="el-icon-time"></i>
        <span> {{ timerNum >= 10 ? timerNum : '0' + timerNum }}秒后刷新 </span>
        <span style="color: rgb(204, 51, 51); cursor: pointer" @click="repositioning">
          刷新</span>
      </div>
      <el-tabs v-model="queryForm.deviceSubStatus" @tab-click="handleClick">
        <el-tab-pane label="全部" name="0">
          <div class="mmv-item" slot="label">
            全部
            <div>({{ carBasicMonitoringCount.allCar }})</div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="行驶" name="1">
          <div class="mmv-item" slot="label">
            行驶
            <div>({{ carBasicMonitoringCount.drivingCar }})</div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="静止" name="2">
          <div class="mmv-item" slot="label">
            静止
            <div>({{ carBasicMonitoringCount.staticCar }})</div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="离线" name="3">
          <div class="mmv-item" slot="label">
            离线
            <div>({{ carBasicMonitoringCount.offlineCar }})</div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="报警" name="4">
          <div class="mmv-item" slot="label" style="color: red">
            报警
            <div>({{ carBasicMonitoringCount.alarmCar }})</div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div>
        <el-date-picker v-model="queryForm.time" :clearable="false" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间" style="width: 100%" />
        <div style="display: flex; margin: 10px 0">
          <el-input v-model="queryForm.carNo" placeholder="请输入车牌号" style="margin-right: 10px"></el-input>
          <el-button type="primary" @click="mmvRef">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>
      <div class="mmv-car-wrap">
        <template v-for="item in carBasicMonitoring">
          <div class="mmv-car-item" :class="{ active: item.carId == nowCar.carId }" :key="item.carId"
            @click="onClickCar(item)">
            <!--                        <i class="el-icon-truck"></i>-->
            <div class="car-item-row">
              <span>{{ item.carNo }}</span>
              <span style="color: red;font-size: 14px;">{{ item.alarmName }}</span>
              <span style="color: green;font-size: 14px;">
                {{ 1 === item.deviceSubStatus ? '行驶' : 2 === item.deviceSubStatus ? '静止' : 3 === item.deviceSubStatus ?
                  '离线' : '' }}</span>
            </div>
            <div class="car-item-row">
              <!-- <el-dropdown trigger="click" @command="changeToggleCarBindInformation">
                <span class="el-dropdown-link" @click="getDevice(item.carId)">
                  设备编号<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="item in devicesList" :key="item.deviceNo" :command="item.deviceNo">{{
                    item.deviceNo
                  }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown> -->

              <el-popover placement="right" width="300" trigger="click" v-model="item.deviceVisible">
                <el-table :data="devicesList">
                  <el-table-column width="150" property="deviceNo" label="设备编号"></el-table-column>
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
                    <template v-slot="{ row }">
                      <span style="color: green;" v-if="item.deviceNo === row.deviceNo">当前</span>
                      <el-button v-else size="small"
                        @click="changeToggleCarBindInformation(row.deviceNo, item)">切换</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button type="text" slot="reference" @click.stop="getDevice(item)">{{ item.deviceNo }}<i
                    class="el-icon-arrow-right el-icon--right"></i></el-button>
              </el-popover>

              <span style="color: #999;font-size: 14px;margin-top: 10px">{{
                1 === item.deviceKind ? '有线' : 2 === item.deviceKind ? '无线' : '' }}</span>
            </div>


            <!--                        <i class="el-icon-location-information"></i>-->
          </div>
        </template>
      </div>
    </div>
    <MmvMap :carBasicMonitoring="carBasicMonitoring" ref="MmvMap" @markerClick="markClick">
    </MmvMap>
    <!--v-loading="timerLoading"-->
    <el-dialog :visible.sync="showInfoWindow" width="950px" :destroy-on-close="true">

      <CarinfoDialog ref="carInfoDialog" :now-car="nowCar" @handleTrace="handleTrace" @handleOrder="handleOrder"
        @handleTrackAnimation="handleTrackAnimation"></CarinfoDialog>

    </el-dialog>

    <el-dialog title="查看轨迹" :visible.sync="showTrackAnimation" width="1100px" append-to-body :destroy-on-close="true">
      <!-- <iframe :src="'./map-track.html?trackPath='+JSON.stringify(trackPath)" style="width:100%;height:580px" frameborder="0"></iframe> -->
      <MmvMapTrack :path="trackPath"></MmvMapTrack>
    </el-dialog>

    <el-dialog title="下发指令" :visible.sync="showzhilin" width="700px" append-to-body :destroy-on-close="true"
      @close="sendinstructions = ''">

      <el-descriptions title="" :column="2">
        <!--        <el-descriptions-item label-class-name="my-descriptions-label" label="设备名称">{{
                  nowCar.carNo || '&#45;&#45;'
                }}
                </el-descriptions-item>-->
        <!-- <el-descriptions-item label-class-name="my-descriptions-label" label="设备IMEI">{{
          nowCar.deviceNo || '--'
        }}
        </el-descriptions-item> -->
        <el-descriptions-item label-class-name="my-descriptions-label" label="设备IMEI">{{

          currentDeviceNo || '--'
        }}
        </el-descriptions-item>
        <el-descriptions-item label-class-name="my-descriptions-label" label="车牌号">{{
          nowCar.carNo || '--'
        }}
        </el-descriptions-item>
        <el-descriptions-item label-class-name="my-descriptions-label" label="车架号">{{
          nowCar.vinNo || '--'
        }}
        </el-descriptions-item>
      </el-descriptions>

      <el-divider></el-divider>

      <el-radio-group v-model="radio" size="middle">
        <el-radio v-for="(item, index) in deviceOrderList" :key="item.id" :label="item.ordername" :value="item.id">

        </el-radio>
        <!--        <span style="font-size: 12px;">({{ item.orderExplain }})</span>-->

      </el-radio-group>
      <!--      <div style="font-size: 13px;color: #999;margin: 5px 0 20px 23px">断油电功能必须在GPS定位状态下才能执行，且速度不能大于20公里/小时，否则延时执行</div>-->

      <!--      <el-form label-width="110px">-->
      <!--        <el-form-item label="设定初始里程" required>-->
      <!--          <el-input v-model="mileage" placeholder="里程"></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-form>-->

      <!--      <div slot="footer" class="dialog-footer">-->
      <!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
      <!--        <el-button @click="showzhilin = false">取 消</el-button>-->
      <!--      </div>-->
    </el-dialog>
  </div>
</template>

<script>
import * as MmvApi from '@/api/mmv'
import MmvMap from './components/map.vue'
import MmvMapTrack from './components/map-track.vue'
import data from './components/data.json'
import { v4 } from 'uuid'
import uilts from "@/utils";
import { getImeiGPSCmd, reportingAddress } from "@/api/mmv";
import CarinfoDialog from "@/views/car/vehiclemonitoringpage/components/carinfo-dialog";
import * as carApi from '@/api/car/car_basic';
import json from 'highlight.js/lib/languages/json'
export default {
  name: 'BaiduMapDemo',
  components: {
    MmvMap,
    MmvMapTrack,
    CarinfoDialog,
  },
  dicts: ['car_status', 'car_repair_status', 'sys_order_source', 'sys_order_status', 'gps_alarm_type'],
  data() {
    return {
      radio: '',
      showzhilin: false,
      mileage: '',
      showTrackAnimation: false,
      carBasicMonitoringCount: {
        allCar: 0,
        drivingCar: 0,
        staticCar: 0,
        offlineCar: 0,
        alarmCar: 0,
      },
      carBasicMonitoring: [],
      queryForm: {
        carNo: '',
        deviceSubStatus: '0',
        pageNum: 1,
        pageSize: 100,
        deviceNo: '',
        time: new Date(),
      },
      nowCar: {},
      trackPath: [],
      timer: null,
      timerNum: 30,
      timerLoading: false,
      startTime: null,
      endTime: null,
      highRecortAddress: '',
      showInfoWindow: false,
      deviceOrderList: [],
      firstEnter: false,
      devicesList: [],
      currentDeviceNo: '', //下发指令当前涉笔
    }
  },
  mounted() {
    if (this.$route.query.id) {
      this.firstEnter = true
    }
    this.getcarBasicMonitoringCount()
    this.getcarBasicMonitoring()
    this.genterateTimer()
    this.getImeiGPSCmd()
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    changeToggleCarBindInformation(deviceNo, item) {
      carApi.toggleCarBindInformation({
        carId: item.carId,
        deviceNo: deviceNo
      }).then(res => {
        item.deviceVisible = false;
        this.mmvRef();
        this.$message.success(res.msg)
      })
    },
    getDevice(item) {
      carApi.carBindInformationList(item.carId).then(res => {
        this.devicesList = res.data;
        this.carBasicMonitoring.map(car => {
          if (item.deviceNo !== car.deviceNo) {
            car.deviceVisible = false;
          }
        })
      })
    },
    submitForm() {
      MmvApi.sendinstructions({
        deviceId: this.nowCar.deviceNo,
        mileage: this.mileage,
      }).then((res) => {
        this.$message.success(res.msg)
      })
    },
    getImeiGPSCmd() {
      MmvApi.getImeiGPSCmd({
        deviceNo: this.nowCar.deviceNo
      }).then(res => {
        this.deviceOrderList = res.data
      })
    },
    genterateTimer() {
      this.timer = setInterval(() => {
        if (this.timerNum >= 1) {
          this.timerNum--
        } else {
          this.repositioning()
        }
      }, 1e3)
    },
    mmvRef() {
      this.timerLoading = true
      this.getcarBasicMonitoringCount().then((response) => {
        return this.getcarBasicMonitoring()
      }).finally(() => {
        this.timerLoading = false
      })


    },

    repositioning() {
      if (this.timerNum < 25) {
        this.timerNum = 30
        clearInterval(this.timer)
        // this.timerLoading = true
        return MmvApi.wodafuCarCurrentLocation()
          .then((response) => {
            return this.getcarBasicMonitoringCount()
          })
          .then((response) => {
            return this.getcarBasicMonitoring()
          })
          .then((response) => {
            //this.timerLoading = false
            this.timerNum = 30
            this.genterateTimer()
          }).finally(() => {
            //  this.timerLoading = false
          })
      } else {
        this.$message.warning('请勿频繁刷新!')
      }

    },
    getcarBasicMonitoringCount() {
      return MmvApi.carBasicMonitoringCount().then((response) => {
        this.carBasicMonitoringCount = response.data
      })
    },
    getcarBasicMonitoring() {
      return MmvApi.carBasicMonitoring(this.queryForm).then((response) => {
        this.carBasicMonitoring = response.rows
        //自定义多设备切换设备显示字段
        this.carBasicMonitoring = this.carBasicMonitoring.map(item => {
          this.$set(item, 'deviceVisible', false);
          return item;
        })

        if (this.firstEnter) {
          this.carBasicMonitoring.forEach(item => {
            if (item.carId === this.$route.query.id) {
              this.onClickCar(item)
            }
          })
          this.firstEnter = false
        }
        console.log('车辆>>>', this.carBasicMonitoring);
      })
    },
    handleClick() {
      // this.getcarBasicMonitoring();
      this.mmvRef()
    },

    onClickCar(item) {
      console.log(item)
      this.nowCar = item
      const point = {
        lng: this.nowCar.lng || 0,
        lat: this.nowCar.lat || 0
      }
      this.$refs.MmvMap.makerCurrentCar(point, this.nowCar);
      // if (item.manufacturer == 5) {
      //   carApi.carOilQuantityt({ id: item.carId }).then((res) => {
      //     if (res.code == 200) {
      //       const point = {
      //         lng: this.nowCar.lng || 0,
      //         lat: this.nowCar.lat || 0
      //       }
      //       const param = {
      //         fuelLevel: res.data?.fuelLevel
      //       }
      //       this.nowCar = { ...item, ...param }

      //       this.$refs.MmvMap.makerCurrentCar(point, this.nowCar);
      //     }
      //   })
      // } else {
      //   this.nowCar = item
      //   const point = {
      //     lng: this.nowCar.lng || 0,
      //     lat: this.nowCar.lat || 0
      //   }
      //   this.$refs.MmvMap.makerCurrentCar(point, this.nowCar);
      // }



    },
    markClick() {
      this.showInfoWindow = true
      this.$nextTick(() => {
        this.$refs.carInfoDialog.getBindDeviceList();
      })
    },

    handleReset() {
      this.nowCar = {}
      this.$refs.MmvMap.handleReset()
      this.mmvRef()
      this.queryForm.carNo = ''
      this.queryForm.time = new Date()
    },
    // 查看轨迹
    handleTrackAnimation(deviceItem) {
      this.timerLoading = true
      const uilts = require('@/utils/index')
      // const deviceNo = this.queryForm.deviceNo || this.nowCar.deviceNo
      const deviceNo = deviceItem.deviceNo || this.nowCar.deviceNo
      this.startTime = uilts.parseTime(
        new Date(this.queryForm.time).getTime() - 24 * 60 * 60 * 1000);
      this.endTime = uilts.parseTime(new Date(this.queryForm.time))
      this.endTime = uilts.parseTime(new Date(this.queryForm.time))

      //新加
      const manufacturer = deviceItem.manufacturer || this.nowCar.manufacturer;
      const simCard = deviceItem.simCard || this.nowCar.simCard;
      MmvApi.getTrack({
        deviceNo: deviceNo,
        trackStartTime: this.startTime,
        trackEndTime: this.endTime,
        // manufacturer: this.nowCar.manufacturer
        manufacturer: manufacturer
      }).then((response) => {
        this.timerLoading = false
        this.trackPath = response.data.trackPlayList || []
        this.jump(deviceNo, manufacturer, response.data.totalMileage, this.nowCar.carNo, simCard, deviceItem)
      })
        .catch((err) => {
          this.timerLoading = false
          // this.trackPath = data
          // setTimeout(() => {
          // this.$message.error('请求服务器错误，现在播放一段示例轨迹')
          // }, 1500)
          // this.jump()
          this.$message.error('暂无轨迹')
        })
    },
    // 实时跟踪
    handleTrace(deviceItem) {
      let routeUrl = this.$router.resolve({
        path: '/map-trace',
        // query: { nowCarNo: this.nowCar.carNo },
        query: { deviceItem: JSON.stringify(deviceItem) },
      })
      window.open(routeUrl.href, '_blank')
    },
    // 下发指令
    handleOrder(deviceItem) {
      this.showzhilin = true
      this.currentDeviceNo = deviceItem.deviceNo;
    },
    jump(deviceNo, manufacturer, totalMileage, carNo, simNo, deviceItem) {
      const id = v4()
      let routeUrl = this.$router.resolve({
        path: '/map-track',
        query: { id: id, aaa: this.startTime, bbb: this.endTime, deviceNo, manufacturer, totalMileage, carNo, simNo, deviceItem: JSON.stringify(deviceItem) },
      })

      sessionStorage.setItem(id, JSON.stringify(this.trackPath))
      window.open(routeUrl.href, '_blank')
    },
  },
}
</script>

<style lang="scss" scoped>
.mmv-map-page {
  display: flex;
  margin: 12px 17px;
  height: calc(100vh - 140px);
}

.mmv-item {
  line-height: 1.1;
  text-align: center;
  font-weight: bold;
}

.mmv-side-bar {
  width: 360px;
  height: 100%;
  padding: 15px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.mmv-car-wrap {
  width: 100%;
  height: calc(100vh - 84px - 200px);
  // height: 500px;
  overflow-y: scroll;
  padding-right: 10px;
}

.mmv-car-item {
  padding: 10px;
  text-align: left;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-top: 5px;
  display: flex;
  flex-direction: column;
  //align-items: center;
  cursor: pointer;

  //span {
  //    flex: 1;
  //    margin: 0 5px;
  //}
  &.active {
    background: #ecf5ff;
    color: #409eff;
    border-color: #409eff;
  }
}

.car-item-row {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.refreshCountdown-carInfo {
  position: absolute;
  // top: 8;
  left: 400px;
  z-index: 20;
  background: #fff;
  border-radius: 4px;
  box-sizing: border-box;
  padding: 5px 20px;
  white-space: nowrap;
}

::v-deep .el-divider {
  background-color: white !important;
  margin: 10px 0 !important;
}

::v-deep .el-dialog__body {
  padding: 0 20px 30px !important;
}

.el-dropdown-link {
  cursor: pointer;
  color: #333;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>
